<template>
  <view class="travel-expense-application">
    <scroll-view class="list-container" scroll-y="true">
      <!-- 顶部操作栏 -->
      <view class="page-header">
        <text class="page-title">差旅费报销申请列表</text>
        <view class="add-button" @click="showAddDialog">
          <uni-icons type="plus" size="20" color="#fff"></uni-icons>
          <text>新增申请</text>
        </view>
      </view>

      <!-- 筛选区域 -->
      <view class="filter-container">
        <view class="filter-bar" @click="openFilter">
          <uni-icons type="filter" size="18" color="#409EFF"></uni-icons>
          <text class="filter-text">筛选</text>
        </view>
        
				<uv-popup ref="filterDrawerRef" mode="bottom" :close-on-click-overlay="true">
          <view class="drawer-content">
            <view class="drawer-header">
              <text>筛选条件</text>
              <uni-icons type="close" size="20" @click="closeFilter"></uni-icons>
            </view>
            
            <uni-forms :model="queryParams" label-position="top">
              <uni-forms-item label="出差人">
                <uni-easyinput v-model="queryParams.businessTripUserName" placeholder="请输入出差人" />
              </uni-forms-item>
              
              <uni-forms-item label="日期范围">
                <uni-datetime-picker
                  type="daterange"
                  v-model="dateRange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </uni-forms-item>
            </uni-forms>
            
            <view class="filter-buttons">
              <button class="btn primary" @click="getApplicationList">查询</button>
              <button class="btn default" @click="resetQuery">重置</button>
            </view>
          </view>
        </uv-popup>
      </view>

      <!-- 申请列表 -->
      <view v-if="applicationList.length === 0" class="empty-state">
        <uni-icons type="info" size="48" color="#ccc"></uni-icons>
        <text class="empty-text">暂无报销申请</text>
      </view>
      
      <view v-else class="card-list">
        <view 
          v-for="(item, index) in applicationList" 
          :key="index" 
          class="application-card"
        >
          <view class="card-header">
            <text class="department">{{ item.departmentName }}</text>
            <uni-tag 
              :text="statusText(item.processStatus)" 
              :type="statusType(item.processStatus)"
              size="small"
            />
          </view>
          
          <view class="card-content">
            <view class="info-row">
              <uni-icons type="user" size="16" color="#666"></uni-icons>
              <text class="info-text">{{ getUserName(item.businessTripUsersList) }}</text>
            </view>
            
            <view class="info-row">
              <uni-icons type="calendar" size="16" color="#666"></uni-icons>
              <text class="info-text">{{ item.businessTripDate }}</text>
            </view>
            
            <view class="info-row">
              <uni-icons type="money" size="16" color="#666"></uni-icons>
              <text class="info-text">报销: ¥{{ item.reimbursementAmount || 0 }}</text>
            </view>
            
            <view class="info-row">
              <uni-icons type="list" size="16" color="#666"></uni-icons>
              <text class="info-text reason">{{ item.businessTripReason }}</text>
            </view>
          </view>
          
          <view class="card-footer">
            <text class="reviewer">审核人: {{ item.reviewUserName || '未指定' }}</text>
            <view class="actions">
              <text class="action-btn view" @click="handleView(item)">查看</text>
              <text 
                v-if="item.processStatus === '0' || item.processStatus === '1'" 
                class="action-btn edit" 
                @click="handleEdit(item)"
              >编辑</text>
              <text 
                v-if="item.processStatus === '3'" 
                class="action-btn edit" 
                @click="handleEdit(item)"
              >重新编辑</text>
              <text 
                v-if="item.processStatus === '0' || item.processStatus === '1' || item.processStatus === '3'" 
                class="action-btn delete" 
                @click="handleDelete(item)"
              >删除</text>
            </view>
          </view>
          
          <!-- 结算信息汇总 -->
          <view class="settlement-summary">
            <view class="settlement-item">
              <text>借款: ¥{{ item.loanAmount || 0 }}</text>
            </view>
            <view class="settlement-item">
              <text>应补: ¥{{ item.supplementAmount || 0 }}</text>
            </view>
            <view class="settlement-item">
              <text>应退: ¥{{ item.retreatAmount || 0 }}</text>
            </view>
            <view class="settlement-item">
              <text>下次借款: ¥{{ item.nextAmount || 0 }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="applicationList.length > 0" class="load-more">
        <text>{{ hasMore ? '加载中...' : '没有更多数据了' }}</text>
      </view>
    </scroll-view>

    <!-- 新增按钮 -->
    <view class="floating-button" @click="showAddDialog">
      <uni-icons type="plus" size="24" color="#fff"></uni-icons>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { 
  travelExpenseReimbursementList,
  travelExpenseReimbursementDel
} from "@/api/documentApproval/travelExpenseReimbursement"

// 响应式数据
const queryParams = reactive({
  businessTripUserName: '',
  businessTripDateStart: '',
  businessTripDateEnd: '',
  pageNum: 1,
  pageSize: 10
})

const dateRange = ref([])
const userInfo = ref({})
const applicationList = ref([])
const total = ref(0)
const hasMore = ref(true)
const filterDrawerRef = ref(null)

// 状态映射函数
const statusText = (status) => {
  const statusMap = {
    '0': '待审批',
    '1': '待复核',
    '2': '审批通过',
    '3': '已驳回'
  }
  return statusMap[status] || '未知'
}

const statusType = (status) => {
  const typeMap = {
    '0': 'warning',
    '1': 'warning',
    '2': 'success',
    '3': 'error'
  }
  return typeMap[status] || 'default'
}

const getUserName = (userList) => {
  if (!userList || !Array.isArray(userList)) return '未知'
  const names = userList.map(user => user.nickName)
  return names.join(', ')
}

// 筛选抽屉控制
const openFilter = () => {
  filterDrawerRef.value?.open()
}

const closeFilter = () => {
  filterDrawerRef.value?.close()
}

// 获取申请列表
const getApplicationList = async () => {
  uni.showLoading({ title: '加载中' })
  
  const params = {
    ...queryParams,
    businessTripDateStart: dateRange.value[0] || '',
    businessTripDateEnd: dateRange.value[1] || '',
    createUser: userInfo.value.userId
  }
  
  try {
    // 模拟延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    const res = await travelExpenseReimbursementList(params)
    applicationList.value = res.rows
    total.value = 2
    hasMore.value = false
  } catch (error) {
    console.error('获取报销申请列表失败:', error)
  } finally {
    uni.hideLoading()
  }
}

// 重置查询条件
const resetQuery = () => {
  Object.assign(queryParams, {
    businessTripUserName: '',
    businessTripDateStart: '',
    businessTripDateEnd: '',
    pageNum: 1,
    pageSize: 10
  })
  dateRange.value = []
  getApplicationList()
  closeFilter()
}

// 页面导航方法
const showAddDialog = () => {
  uni.navigateTo({
    url: '/pages/documentApproval/travelExpenseReimbursementForm?handle=add'
  })
}

const handleEdit = (row) => {
  uni.navigateTo({
    url: `/pages/documentApproval/travelExpenseReimbursementForm?handle=edit&id=${row.id}`
  })
}

const handleView = (row) => {
  uni.navigateTo({
    url: `/pages/documentApproval/travelExpenseReimbursementForm?handle=view&id=${row.id}`
  })
}

const handleDelete = (row) => {
  uni.showModal({
    title: '提示',
    content: '确认删除该报销申请吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await travelExpenseReimbursementDel(row.id)
          uni.showToast({ title: '删除成功' })
          getApplicationList()
        } catch (error) {
          console.error('删除报销申请失败:', error)
          uni.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    }
  })
}

// 生命周期钩子
onLoad(() => {
  userInfo.value = uni.getStorageSync('userInfo') || {}
  getApplicationList()
})
</script>

<style scoped>
.travel-expense-application {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
}

.add-button {
  display: flex;
  align-items: center;
  background-color: #409EFF;
  color: #fff;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.add-button text {
  margin-left: 4px;
}

.filter-container {
  background-color: #fff;
  padding: 15px;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}

.filter-bar {
  display: flex;
  align-items: center;
  color: #409EFF;
}

.filter-text {
  margin-left: 5px;
  font-size: 14px;
}

.drawer-content {
  padding: 20px;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
  font-weight: bold;
}

.filter-buttons {
  display: flex;
  margin-top: 20px;
}

.filter-buttons .btn {
  flex: 1;
  margin: 0 5px;
  border-radius: 4px;
}

.filter-buttons .primary {
  background-color: #409EFF;
  color: #fff;
}

.filter-buttons .default {
  background-color: #f5f7fa;
  color: #606266;
}

.list-container {
  height: calc(100vh - 60px);
  padding: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
}

.empty-text {
  margin-top: 10px;
  font-size: 14px;
}

.card-list {
  padding-bottom: 10px;
}

.application-card {
  background: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.department {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.card-content {
  margin-bottom: 12px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-text {
  margin-left: 6px;
  font-size: 14px;
  color: #606266;
  flex: 1;
}

.reason {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.reviewer {
  font-size: 13px;
  color: #909399;
}

.actions {
  display: flex;
}

.action-btn {
  margin-left: 12px;
  font-size: 13px;
  padding: 4px 8px;
  border-radius: 4px;
}

.view {
  color: #409EFF;
  background-color: #ecf5ff;
}

.edit {
  color: #67c23a;
  background-color: #f0f9eb;
}

.delete {
  color: #f56c6c;
  background-color: #fef0f0;
}

.settlement-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #eee;
}

.settlement-item {
  background-color: #f8f9fa;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.load-more {
  text-align: center;
  padding: 15px;
  color: #999;
  font-size: 13px;
}

.floating-button {
  position: fixed;
  right: 20px;
  bottom: 80px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
  z-index: 999;
}
</style>